package com.db.stexchem.server;

import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.db.stexchem.exceptions.BadRequestException;
import com.db.stexchem.message.Order;

public class OrderService {
  
  private final Logger               logger         = LoggerFactory
                                                        .getLogger(OrderService.class);
  private final Set<String>          stocks;
  private final OrderBook            orderBook;
  private int                        currentOrderNo = 0;
  
  public OrderService(Set<String> stocks) {
    this.stocks = stocks;
    orderBook = new OrderBook(stocks);
  }
  
  public void checkOrder(final Order order) throws BadRequestException {
    logger.trace("checking order ...");
    if (!stocks.contains(order.getStockName())) {
      throw new BadRequestException("Illegal stock name: '"
          + order.getStockName() + "'");
    }
    if (order.getNShares() <= 0) {
      throw new BadRequestException("Number of shares must be positive value");
    } else if (order.getPrice() != null && order.getPrice() <= 0) {
      throw new BadRequestException("Price must be positive value");
    } else {
      logger.trace("order has been successfully checked");
    }
  }
  
  public synchronized int getNextOrderNo() {
    return currentOrderNo++;
  }
  
  public synchronized List<Match> placeOrder(final Order order) {
    logger.info("placing {} to the order book ...", order);
    return orderBook.add(order);
  }
}
